<template>
    <div :class="{my : messageData.userType === 1}" class="wrapper MessageItem">

        <span class="time" v-if="messageData.showMessageTime" v-show="showTime">{{messageData.messageTime}}</span>
        <div class="group-notice withdraw" v-if="messageData.status === false">{{`该消息已被撤回`}}</div>
        <div class="content-box" v-else-if="messageData.messageType !== 4">
            <div class="avatar-box">
                <img :src="messageData.userInfo.avatar" alt="" draggable="false">
            </div>
            <div class="content-container">
                <div class="group-cn" v-if="showAlias">{{messageData.groupAlias}}</div>
                <div class="group-cn" v-if="!showAlias && isFav">{{messageData.favText || messageData.groupAlias}}</div>
                <div class="message-box" v-if="messageData.messageType === 1" @mousedown.right.prevent="onmousedownRight(messageData)">
                    <span class="message">{{messageData.messageText}}</span>
                    <i :class="{loading : messageData.status === 0, error : messageData.status === -1}" v-if="messageData.status !== 1"></i>
                </div>
                <div class="message-img-box" v-else-if="messageData.messageType === 2" @mousedown.right.prevent="onmousedownRight(messageData)">
                    <i :class="{loading : messageData.status === 0, error : messageData.status === -1}" v-if="messageData.status !== 1"></i>
                    <EasyPreview :img-src="messageData.messageImgUrl">
                        <img :src="messageData.messageImgUrl" alt="" class="pic" @click="showMaskView"/>
                    </EasyPreview>
                </div>
<!--                <a :href="messageData.fileInfo.downloadUrl" :download="messageData.fileInfo.fileName" target="_blank" class="message-file-box" v-else-if="messageData.messageType === 3" @mousedown.right.prevent="onmousedownRight(messageData)">-->
<!--                    <div class="preview">-->
<!--                        <img src="../assets/icon/icon-unknown.png" class="prev-img" alt=""/>-->
<!--                    </div>-->
<!--                    <div class="detail">-->
<!--                    <span class="title">-->
<!--                        {{messageData.fileInfo.fileName}}-->
<!--                    </span>-->
<!--                        <span class="size">{{messageData.fileInfo.fileSize}}</span>-->
<!--                    </div>-->
<!--                    <div class="progress-box" v-show="(messageData.status === 0) || (messageData.status === -1)">-->
<!--                        <el-progress :text-inside="true" :show-text="false" :stroke-width="5" :percentage="messageData.percentage"></el-progress>-->
<!--                    </div>-->
<!--                </a>-->
              <div @click="getDownloadFileName(messageData.fileInfo.downloadUrl)" class="message-file-box" v-else-if="messageData.messageType === 3" @mousedown.right.prevent="onmousedownRight(messageData)">
                  <div class="preview">
                    <img src="../assets/icon/icon-unknown.png" class="prev-img" alt=""/>
                  </div>
                  <div class="detail">
                      <span class="title">
                          {{messageData.fileInfo.fileName}}
                      </span>
                    <span class="size">{{messageData.fileInfo.fileSize}}</span>
                  </div>
                  <div class="progress-box" v-show="(messageData.status === 0) || (messageData.status === -1)">
                    <el-progress :text-inside="true" :show-text="false" :stroke-width="5" :percentage="messageData.percentage"></el-progress>
                  </div>
              </div>
            </div>
        </div>
        <div class="group-notice" v-else-if="messageData.messageType === 4">{{messageData.messageText}}</div>
        <span class="errText" v-if="messageData.status === -1">{{messageData.errText}}</span>

        <select-box :select-list-data="operationList" v-if="showSelectBox"
                    @clickCancel="onClickCancel" @clickConfirm="onClickConfirm"
                    @clickClose="onClickClose">
        </select-box>
    </div>


</template>

<script>
    import {getTalkList} from "../api/user";
    import {sendMessage} from "../api/indexWS";
    import selectBox from "./SelectBox";
    import {messageCacheMap} from "../util/CacheMap";
    import {addFavor} from "../api/favor";
    import {withdraw} from "../api/talk";
    import {fileDownload} from "../util/fileUtil";

    export default {
        name: "messageItem",
        components: {selectBox},
        data : function () {
            return {
                showBigImg : false,
                operationList: [],
                showSelectBox: false,

            }
        },
        props : {
            messageData : {
                type : Object,
                default () {
                    return {}
                }
            },
            showAlias : {
                default : false
            },
            showTime: {
                default() {
                  return true;
                }
            },
            favText: {
              default() {
                return '';
              }
            },
            isFav: {
              default() {return false}
            }
        },
        methods : {
            showMaskView(){
                this.showBigImg = true;
            },
            closeMaskView(){
                this.showBigImg = false;
            },
            onmousedownRight(data) {
                // console.log("??")
                // let talkId = data.talkId;
                // if (!talkId){
                //   console.log("没有talkId");
                //   return
                // }
                console.log(this.$route.name);
                if (this.$route.name === 'favor') {
                  return;
                }
                const renderList = [
                  {
                    renderText : "转发消息",
                    clickEvent : async (data) => {
                      let {talkList} = await getTalkList();
                      this.showSelectBox = true;
                      this.operationList = talkList.map((value) => {
                        return {
                          text: value.talkTitle,
                          imgUrl: value.avatar,
                          key: value.talkId,
                          payload: value
                        }
                      })
                    }
                  },
                  // {
                  //     renderText : "收藏消息",
                  //     clickEvent : (data) => {
                  //         addFavor(data.payload.messageId, {
                  //           favText: this.favText,
                  //           ...data.payload,
                  //         }).then(() => {
                  //             this.$message.success("收藏成功");
                  //         })
                  //     }
                  // },
                ];
                if (this.messageData.userType === 1) {
                  renderList.push({
                    renderText : "撤回消息",
                    clickEvent : (data) => {
                      let {talkId} = this.$route.params;
                      let messageId = data.payload.messageId;
                      this.bus.$emit('withdrawMessage', {talkId, messageId});
                      withdraw(talkId, messageId);
                      console.log('messageItem撤回消息：talkId:',talkId, 'messageId: ',messageId);
                    }
                  });
                }
                this.bus.$emit("openContextMenu", {
                    event,
                    renderList : renderList,
                    payload : {
                        ...data
                    }
                })
            },
            onClickCancel() {
                this.showSelectBox = false;
                // this.selectType = 0;
            },
            getDownloadFileName(url) {
              // this.$prompt('请输入下载文件名', '提示', {
              //   confirmButtonText: '确定',
              //   cancelButtonText: '取消'
              // }).then(({ value }) => {
              //   this.$message({
              //     type: 'success',
              //     message: '开始下载'
              //   });
              //   this.download(url, value);
              // }).catch(() => {
              //   this.$message({
              //     type: 'info',
              //     message: '取消下载'
              //   });
              // });
              // 不用重命名的原因是....需要同源策略
              this.$confirm('是否下载文件', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'info'
              }).then(() => {
                this.$message({
                  type: 'success',
                  message: '开始下载'
                });
                this.download(url);
              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '取消下载'
                });
              });

            },
            async onClickConfirm(data) {
                // let type = this.selectType;
                this.showSelectBox = false;
                let messageData = this.messageData;
                let timeStamp = new Date().getTime().toString();
                for (let i = 0; i < data.length; i++) {
                    let genData = {
                        messageText: messageData.messageText,
                        messageType: messageData.messageType,
                        talkId: data[i].talkId,
                        srcId: localStorage.uid,
                        destId: data[i].friendId || data[i].gid,
                        messageImgUrl: messageData.messageImgUrl,
                        fileInfo: messageData.fileInfo,
                        timeStamp: timeStamp,
                        isGroup: !!data[i].gid,
                        gid: data[i].gid
                    };
                    messageCacheMap.set(`${data[i].talkId}-${timeStamp}`, genData);
                    console.log('转发消息', `handleForwardMessage fire`)
                    this.bus.$emit('handleForwardMessage', {
                      messageId: messageData.messageId,
                      talkId: genData.talkId,
                      messageText: messageData.messageText || ((messageData.messageType === 2) ? '[图片]': messageData.fileInfo.fileName),
                      timeStamp: `${timeStamp}`
                    });
                    sendMessage(genData);
                }
                // if (type === 1){
                //     this.__inviteFriend(data);
                // } else if (type === 2){
                //     this.__deleteMember(data);
                // }
            },
            onClickClose() {
                this.showSelectBox = false;
                // this.selectType = 0;
            },
            async download(url, fileName) {
                // fileDownload(url, fileName);
                console.log(fileDownload, url, fileName);
                const link = document.createElement('a')
                // 设置a标签的href（点击地址）
                link.href = url;
                // 设置a标签属性
                link.setAttribute('download', fileName);
                // 点击a标签
                document.body.appendChild(link)
                link.click()
                // 移除a标签
                document.body.removeChild(link)

            },

        }
    }
</script>

<style scoped lang="less">
    @import "../assets/style/components/MessageItem.less";
</style>
